package com.icode.gulimall.ware.controller;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

import com.icode.common.exception.NoStockException;
import com.icode.common.to.SkuHasStockVo;
import com.icode.common.utils.R;
import com.icode.gulimall.ware.vo.WareSkuLockVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import com.icode.gulimall.ware.entity.WareSkuEntity;
import com.icode.gulimall.ware.service.WareSkuService;
import com.icode.common.utils.PageUtils;


import static com.icode.common.exception.BizCodeEnum.NO_STOCK_EXCEPTION;


/**
 * 商品库存
 *
 * @author my_code
 * @email my_code@foxmail.com
 * @date 2020-11-21 23:12:34
 */
@RestController
@RequestMapping("ware/waresku")
public class WareSkuController {

    @Autowired
    private WareSkuService wareSkuService;

    @PostMapping("/checkItemsStock")
    public R checkItemsStock(@RequestParam Map<String, String> skuInfo) {
        Map<Long, Boolean> booleanMap = wareSkuService.checkItemsStock(skuInfo);
        return R.ok().setData(booleanMap);
    }

    @PostMapping("/lockstock")
    public R lockItemsStock(@RequestBody WareSkuLockVo lockVo){
        try {
            wareSkuService.lockItemsStock(lockVo);
            return R.ok();
        } catch (NoStockException e) {
            return R.error(NO_STOCK_EXCEPTION.getCode(), NO_STOCK_EXCEPTION.getMsg());
        }
    }

    @PostMapping("/checkHasStock")
    public R checkHasStockBySkuId(@RequestBody List<Long> skuIds) {
        List<SkuHasStockVo> skuHasStockVos = wareSkuService.checkWareStockBySkuId(skuIds);
        return R.ok().setData(skuHasStockVos);
    }

    /**
     * 列表
     */
    @RequestMapping("/list")
    public R list(@RequestParam Map<String, Object> params) {
        PageUtils page = wareSkuService.queryPage(params);

        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    public R info(@PathVariable("id") Long id) {
        WareSkuEntity wareSku = wareSkuService.getById(id);
        return R.ok().put("wareSku", wareSku);
    }

    /**
     * TODO 保存优化，不保存重复的sku，保存后弹窗关闭
     * 保存
     */
    @RequestMapping("/save")
    public R save(@RequestBody WareSkuEntity wareSku) {
        wareSkuService.save(wareSku);

        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    public R update(@RequestBody WareSkuEntity wareSku) {
        wareSkuService.updateById(wareSku);

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    public R delete(@RequestBody Long[] ids) {
        wareSkuService.removeByIds(Arrays.asList(ids));

        return R.ok();
    }

}
